﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using GestionIncidencias.Models;


namespace GestionIncidencias.Controllers
{
    public class ServicioController : Controller
    {

        private string servicioRESTService = "http://localhost:8090/Servicios.svc/Servicios";
        JavaScriptSerializer js = new JavaScriptSerializer();

          

        public ActionResult Index()
        {




            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(servicioRESTService);
            req.Method = "GET";
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader reader = new StreamReader(res.GetResponseStream());
            string serviciosJson = reader.ReadToEnd();
            List<Servicio> servicios = js.Deserialize<List<Servicio>>(serviciosJson);

            return View(servicios);
            
        }


        //
        // GET: /Servicio/Details/5

        public ActionResult Details(int id)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(servicioRESTService + "/" + id);
            req.Method = "GET";
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader reader = new StreamReader(res.GetResponseStream());
            string serviciosJson = reader.ReadToEnd();
            Servicio servicio = js.Deserialize<Servicio>(serviciosJson);

            return View(servicio);
        }

        //
        // GET: /Servicio/Create

        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /Servicio/Create

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {

            try
            {
                string postdata = "{\"Codigo\":\"" + collection["Codigo"] + "\",\"Nombre\":\"" + collection["Nombre"] + "\",\"Descripcion\":\"" + collection["Descripcion"] + "\" }";

                byte[] data = Encoding.UTF8.GetBytes(postdata);
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(servicioRESTService);
                req.Method = "POST";
                req.ContentLength = data.Length;
                req.ContentType = "application/json";
                var reqStream = req.GetRequestStream();
                reqStream.Write(data, 0, data.Length);

                var res = (HttpWebResponse)req.GetResponse(); // si no falla retorna al mantenimiento 
                return RedirectToAction("Index");
            }
            catch (WebException wex) {

                HttpWebResponse resError = (HttpWebResponse)wex.Response;
                StreamReader reader2 = new StreamReader(resError.GetResponseStream());
                string error = reader2.ReadToEnd();
                string errorFull = "{\"CodigoNegocio\":\"" + collection["Codigo"] + 
                    "\",\"MensajeNegocio\":\"" + "El Servicio con codigo: " + collection["Codigo"] + " ó el Nombre: " + 
                    collection["Nombre"] + " ya existe en la base de datos" + "\" }";

                JavaScriptSerializer js = new JavaScriptSerializer();
                Error objetoError = js.Deserialize<Error>(errorFull);
             
                Session["objetoError"] = objetoError;

                ModelState.AddModelError("Error", wex.Message);

                return View();
            }
            catch (Exception e)
            {
                ModelState.AddModelError("Error", e.Message);
                return View();
            }
        }
        
        //
        // GET: /Servicio/Edit/5
 
        public ActionResult Edit(int id)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(servicioRESTService + "/" + id);
            req.Method = "GET";
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader reader = new StreamReader(res.GetResponseStream());
            string servicioJson = reader.ReadToEnd();
            Servicio servicio = js.Deserialize<Servicio>(servicioJson);
            return View(servicio);

        }

        //
        // POST: /Servicio/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {

            try
            {
                string postdata = "{\"Codigo\":\"" + id + "\",\"Nombre\":\"" + collection["Nombre"] + "\",\"Descripcion\":\"" + collection["Descripcion"] + "\" }";
                byte[] data = Encoding.UTF8.GetBytes(postdata);
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(servicioRESTService);
                req.Method = "PUT";
                req.ContentLength = data.Length;
                req.ContentType = "application/json";
                var reqStream = req.GetRequestStream();
                reqStream.Write(data, 0, data.Length);
                var res = (HttpWebResponse)req.GetResponse();
                return RedirectToAction("Index");


            }
            catch
            {
                return View();
            }

        }

        //
        // GET: /Servicio/Delete/5
 
        public ActionResult Delete(int id)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(servicioRESTService + "/" + id);
            req.Method = "GET";
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader reader = new StreamReader(res.GetResponseStream());
            string servicioJson = reader.ReadToEnd();
            Servicio servicio = js.Deserialize<Servicio>(servicioJson);
            return View(servicio);

        }

        //
        // POST: /Servicio/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                string postdata = "\"" + id + "\"";
                byte[] data = Encoding.UTF8.GetBytes(postdata);
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(servicioRESTService);
                req.Method = "DELETE";
                req.ContentLength = data.Length;
                req.ContentType = "application/json";
                var reqStream = req.GetRequestStream();
                reqStream.Write(data, 0, data.Length);
                var res = (HttpWebResponse)req.GetResponse();
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
